/**
 * @description: 文件下载
 * @fileName: fileSave
 * @author: luhuixu
 * @date: 2023/7/27-22:00
 * @version: V1.0.0
 **/
import { saveAs } from 'file-saver'

/**
 * 下载压缩包文件
 * @param {blob} fileArrayBuffer 文件流
 * @param {String} filename 文件名称
 * @param {String} fileType 文件格式
 */
export const downloadZip = (fileArrayBuffer, filename, fileType) => {
  const data = new Blob([fileArrayBuffer], { type: fileType === 'zip' ? 'application/zip,charset=utf-8' : 'application/x-rar-compressed,charset=utf-8' })
  if (typeof window.chrome !== 'undefined') {
    // Chrome
    var link = document.createElement('a')
    link.href = window.URL.createObjectURL(data)
    link.download = filename
    link.click()
    console.log(data)
  } else if (typeof window.navigator.msSaveBlob !== 'undefined') {
    // IE
    var blob = new Blob([data], { type: fileType === 'zip' ? 'application/zip' : 'application/x-rar-compressed' })
    window.navigator.msSaveBlob(blob, filename)
  } else {
    // Firefox
    var file = new File([data], filename, { type: fileType === 'zip' ? 'application/zip' : 'application/x-rar-compressed' })
    window.open(URL.createObjectURL(file))
  }
}
/**
 * @params {stream} fileStream 服务器返回的文件流
 * @params {string} saveFileName 下载的文件名称
 * @retuen {promise}
 */
export const downloadFile = (fileStream, saveFileName) => {
  return new Promise((resolve, reject) => {
    const blob = new Blob([fileStream])
    if (navigator.msSaveBlob) {
      // 兼容IE
      navigator.msSaveBlob(blob, saveFileName)
    } else {
      const url = window.URL.createObjectURL(blob)
      saveAs(url, saveFileName)
    }
    resolve()
  })
}
